<template>
  <div class="flow-designer">
    <div class="flow-designer-content">
      <section class="dingflow-design">
        <div class="zoom">
          <div class="zoom-out" :class="nowVal == 50 && 'disabled'" @click="zoomSize(1)"></div>
          <span>{{ nowVal }}%</span>
          <div class="zoom-in" :class="nowVal == 300 && 'disabled'" @click="zoomSize(2)"></div>
          <!-- <div class="zoom-in" :class="nowVal == 300 && 'disabled'" @click="getNodeConfigs"></div> -->
        </div>
        <div class="box-scale" :style="`transform: scale(${nowVal / 100});`">
          <nodeWrap v-model:nodeConfig="nodeConfig" :internal-state="internalState" />
          <div class="end-node">
            <div class="end-node-circle"></div>
            <div class="end-node-text">流程结束</div>
          </div>
        </div>
      </section>
    </div>
    <errorDialog v-model:visible="tipVisible" :list="tipList" />
    <promoterDrawer />
    <approverDrawer :directorMaxLevel="directorMaxLevel" />
    <copyerDrawer />
    <conditionExpressionDrawer />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, provide } from 'vue'
import errorDialog from './dialog/errorDialog.vue'
import promoterDrawer from './drawer/promoterDrawer.vue'
import approverDrawer from './drawer/approverDrawer.vue'
import copyerDrawer from './drawer/copyerDrawer.vue'
import conditionExpressionDrawer from './drawer/conditionExpressionDrawer.vue'
import nodeWrap from './nodeWrap.vue'

// Props
const props = defineProps({
  // v-model支持
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  // API函数配置
  apiConfig: {
    type: Object,
    default: () => ({
      getRoles: null,
      getDepartments: null,
      getEmployees: null,
      getConditions: null,
    }),
  },
  // 表单配置，用于条件表达式中的表单变量
  formConfig: {
    type: Object,
    default: () => ({ fields: [] }),
  },
})

// Emits
const emit = defineEmits(['return', 'save', 'change', 'update:modelValue', 'validate'])

// 内部状态管理
const internalState = reactive({
  nodeConfigMap: {},
  promoterDrawer: false,
  flowPermission1: {},
  approverDrawer: false,
  approverConfig1: {},
  copyerDrawer: false,
  copyerConfig1: {},
  conditionDrawer: false,
  conditionsConfig1: {
    conditionNodes: [],
  },
})

// 提供内部状态给子组件
provide('flowDesignerState', {
  state: internalState,
  apiConfig: props.apiConfig,
  formConfig: props.formConfig,
  actions: {
    putNodeConfig(id, config) {
      internalState.nodeConfigMap[id] = config
    },
    getNodeConfig(id) {
      return internalState.nodeConfigMap[id]
    },
    setPromoter(payload) {
      internalState.promoterDrawer = payload
    },
    setFlowPermission(payload) {
      internalState.flowPermission1 = payload
    },
    setApprover(payload) {
      internalState.approverDrawer = payload
    },
    setApproverConfig(payload) {
      internalState.approverConfig1 = payload
    },
    setCopyer(payload) {
      internalState.copyerDrawer = payload
    },
    setCopyerConfig(payload) {
      internalState.copyerConfig1 = payload
    },
    setCondition(payload) {
      internalState.conditionDrawer = payload
    },
    setConditionsConfig(payload) {
      internalState.conditionsConfig1 = payload
    },
  },
})

// 响应式数据
const tipList = ref([])
const tipVisible = ref(false)
const nowVal = ref(100)
const nodeConfig = ref({})
const flowPermission = ref([])
const directorMaxLevel = ref(0)

// 手动触发数据同步的函数
// const emitDataChange = () => {
//   emit('update:modelValue', nodeConfig.value)
//   emit('change', nodeConfig.value)

//   // 触发验证
//   const isValid = validateConfig()
//   emit('validate', isValid)
// }

// 初始化数据
onMounted(() => {
  nodeConfig.value = props.modelValue
})

// 错误检查递归函数
const reErr = ({ childNode }) => {
  if (childNode) {
    const { type, error, nodeName, conditionNodes } = childNode
    if (type == 1 || type == 2) {
      if (error) {
        tipList.value.push({
          name: nodeName,
          type: ['', '审核人', '抄送人'][type],
        })
      }
      reErr(childNode)
    } else if (type == 3) {
      reErr(childNode)
    } else if (type == 4) {
      reErr(childNode)
      for (let i = 0; i < conditionNodes.length; i++) {
        if (conditionNodes[i].error) {
          tipList.value.push({ name: conditionNodes[i].nodeName, type: '条件' })
        }
        reErr(conditionNodes[i])
      }
    }
  } else {
    childNode = null
  }
}

// // 保存处理
// const handleSave = () => {
//   internalState.isTried = true
//   tipList.value = []
//   reErr(nodeConfig.value)

//   if (tipList.value.length != 0) {
//     tipVisible.value = true
//     return
//   }

//   processConfig.value.flowPermission = flowPermission.value

//   // 触发数据变化事件
//   emitDataChange()

//   // 触发保存事件，让父组件处理具体的保存逻辑
//   emit('save', processConfig.value)
// }

// 验证配置函数
const validateConfig = () => {
  tipList.value = []
  reErr(nodeConfig.value)
  if (tipList.value.length != 0) {
    tipVisible.value = true
    return false
  }
  return true
}

// 缩放功能
const zoomSize = (type) => {
  if (type == 1) {
    if (nowVal.value == 50) {
      return
    }
    nowVal.value -= 10
  } else {
    if (nowVal.value == 300) {
      return
    }
    nowVal.value += 10
  }
}

const getNodeConfigs = () => {
  console.log(internalState.nodeConfigMap)
}

// 暴露方法给父组件
defineExpose({
  // 获取当前配置
  getConfig: () => ({
    nodeConfig: nodeConfig.value,
    flowPermission: flowPermission.value,
    directorMaxLevel: directorMaxLevel.value,
  }),
  // 设置配置
  setConfig: (config) => {
    nodeConfig.value = config
  },
  // 验证配置
  validate: () => {
    // internalState.isTried = true
    // tipList.value = []
    // reErr(nodeConfig.value)
    return validateConfig()
  },
  // 重置验证状态
  resetValidation: () => {
    tipList.value = []
    tipVisible.value = false
  },
})
</script>

<style>
@import 'css/workflow.css';
@import 'css/override-element-ui.css';
.flow-designer {
  width: 100%;
  height: 100%;
}

.flow-designer-content {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  /* padding-bottom: 10px; */
}

.flow-designer-content .dingflow-design {
  position: relative;
  width: 100%;
  min-height: calc(100vh - 320px);
  height: auto;
  background-color: #f5f5f7;
  overflow: auto;
}

.flow-designer-content .zoom {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  width: 125px;
  z-index: 10;
  margin-top: 0;
}
.error-modal-list {
  width: 455px;
}

.clear:before,
.clear:after {
  content: ' ';
  display: table;
}

.clear:after {
  clear: both;
}

.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.l {
  float: left;
}

input {
  text-indent: 10px;
}

select {
  text-indent: 8px;
}

.ml_10 {
  margin-left: 10px;
}

.mr_10 {
  margin-right: 10px;
}

.radio_box a,
.check_box a {
  font-size: 12px;
  position: relative;
  padding-left: 20px;
  margin-right: 30px;
  cursor: pointer;
  color: #333;
  white-space: pre;
}

.check_box.not a:hover {
  color: #333;
}

.check_box.not a::before,
.check_box.not a:hover::before {
  border: none;
}

.check_box.not.active {
  background: #f3f3f3;
}

.radio_box a:hover::before,
.check_box a:hover::before {
  border: 1px solid #46a6fe;
}

.radio_box a::before,
.check_box a::before {
  position: absolute;
  width: 14px;
  height: 14px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  left: 0;
  top: 1px;
  content: '';
}

.radio_box a::before {
  border-radius: 50%;
}

.check-dot.active::after,
.radio_box a.active::after,
.check_box a.active::after {
  position: absolute;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  top: 3px;
  left: 3px;
  content: '';
}

.radio_box a.active::after {
  background: #46a6fe;
}

.check_box a.active::after {
  background: url(images/check_box.png) no-repeat center;
}
</style>
